<template>
    <PageTitle>
        Редактирование изображений проекта: {{ $route.params.projectId }}
    </PageTitle>

    <ErrorAlert :message="error" v-if="error" />
    <SuccessAlert :message="successAlertMessage" v-if="submitSuccessful" />

    <FormProjectImages v-if="!loading" :images="images" v-on:sumbitform="send" />

    <Spinner v-else-if="loading" />
</template>

<script>
import FormProjectImages from "@/components/projects/FormProjectImages.vue";

export default {
    components: {
        FormProjectImages
    },
    data() {
        return {
            loading: false,
            error: null,
            submitSuccessful: false,
            successAlertMessage: "Изображения проекта успешно изменены",
            images: {
                card: null,
                slider: null,
            },
        }
    },
    created() {
        this.load();
    },
    methods: {
        send(images) {
            console.log(images)
            const formData = new FormData();
            formData.append('cardImage', images.card);
            for (let i = 0; i < images.slider.length; i++) {
                formData.append('sliderImages', images.slider.item(i));
                console.log(images.slider.item(i))
            }

            const url = "/api/Projects/UploadImages/" + this.$route.params.projectId;
            const requestOptions = {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + this.$store.state.token,
                },
                body: formData
            };
            fetch(url, requestOptions)
                .then(response => {
                    if (response.status === 200) {
                        this.$router.push("/Projects/" + this.$route.params.projectId);
                    }
                    else {
                        console.log(response);
                        this.error = "Во время изменения изображений возникла ошибка. (" + response.status + ": " + response.statusText + ")";
                    }
                })
        },
        load() {
            this.loading = true;
            this.images = {
                card: null,
                slider: null,
            },
            this.loading = false;
        }
    }
}
</script>

<style lang="scss" scoped></style>